<template>
  <view class="page">
    <!-- 通知统计 -->
    <view class="header">
      <view class="stats">
        <text class="total-count">共 {{ totalCount }} 条通知</text>
        <text class="unread-count" v-if="unreadCount > 0">{{ unreadCount }} 条未读</text>
      </view>
      <view class="actions">
        <button class="mark-all-btn" @click="markAllAsRead" v-if="unreadCount > 0">
          全部已读
        </button>
        <button class="clear-btn" @click="clearReadNotifications">
          清空已读
        </button>
      </view>
    </view>

    <!-- 通知列表 -->
    <view class="content">
      <view v-if="loading" class="loading">加载中...</view>
      <view v-else-if="notificationList.length === 0" class="empty">
        <image src="/static/img/empty.png" class="empty-img" mode="aspectFit"></image>
        <text class="empty-text">暂无通知消息</text>
      </view>
      <view v-else class="list">
        <view 
          v-for="item in notificationList" 
          :key="item.id" 
          :class="['notification-item', item.is_read ? 'read' : 'unread']"
          @click="handleNotificationClick(item)"
        >
          <view class="notification-header">
            <view class="notification-type">
              <text :class="['type-icon', getTypeClass(item.type)]">
                {{ getTypeIcon(item.type) }}
              </text>
              <text class="type-text">{{ getTypeText(item.type) }}</text>
            </view>
            <view class="notification-time">
              {{ formatTime(item.send_time) }}
            </view>
          </view>
          
          <view class="notification-content">
            <text class="notification-title">{{ item.title }}</text>
            <text class="notification-text">{{ item.content }}</text>
          </view>

          <view class="notification-footer">
            <view class="read-status">
              <view v-if="!item.is_read" class="unread-dot"></view>
              <text class="read-text">{{ item.is_read ? '已读' : '未读' }}</text>
            </view>
            <view class="notification-actions">
              <button class="action-btn" @click.stop="markAsRead(item)" v-if="!item.is_read">
                标记已读
              </button>
              <button class="action-btn delete" @click.stop="deleteNotification(item)">
                删除
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view v-if="hasMore" class="load-more" @click="loadMore">
      <text>点击加载更多</text>
    </view>
  </view>
</template>

<script>
import { myRequest } from '@/util/request.js';

export default {
  name: 'NotificationList',
  data() {
    return {
      notificationList: [],
      totalCount: 0,
      unreadCount: 0,
      loading: false,
      page: 1,
      limit: 20,
      hasMore: false
    };
  },
  onLoad() {
    this.fetchNotifications();
    this.getUnreadCount();
  },
  onShow() {
    // 从其他页面返回时刷新
    this.fetchNotifications();
    this.getUnreadCount();
  },
  onPullDownRefresh() {
    this.page = 1;
    this.notificationList = [];
    this.fetchNotifications().finally(() => {
      uni.stopPullDownRefresh();
    });
  },
  methods: {
    async fetchNotifications(loadMore = false) {
      if (!loadMore) {
        this.loading = true;
      }
      
      try {
        const data = await myRequest({
          url: '/api/notifications',
          method: 'GET',
          data: {
            page: this.page,
            limit: this.limit
          }
        });
        
        const newNotifications = data.notifications || [];
        
        if (loadMore) {
          this.notificationList = [...this.notificationList, ...newNotifications];
        } else {
          this.notificationList = newNotifications;
        }
        
        this.totalCount = data.pagination?.total || 0;
        this.hasMore = this.notificationList.length < this.totalCount;
      } catch (e) {
        console.error('获取通知列表失败', e);
        uni.showToast({ title: '获取通知失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },

    async getUnreadCount() {
      try {
        const data = await myRequest({
          url: '/api/notifications/unread-count',
          method: 'GET'
        });
        this.unreadCount = data.unreadCount || 0;
      } catch (e) {
        console.error('获取未读数量失败', e);
      }
    },

    async markAsRead(item) {
      try {
        await myRequest({
          url: `/api/notifications/${item.id}/read`,
          method: 'PUT'
        });
        item.is_read = 1;
        item.read_time = new Date().toISOString();
        this.unreadCount = Math.max(0, this.unreadCount - 1);
        uni.showToast({ title: '已标记为已读', icon: 'success' });
      } catch (e) {
        console.error('标记已读失败', e);
        uni.showToast({ title: '操作失败', icon: 'none' });
      }
    },

    async markAllAsRead() {
      try {
        await myRequest({
          url: '/api/notifications/read-all',
          method: 'PUT'
        });
        // 更新本地数据
        this.notificationList.forEach(item => {
          if (!item.is_read) {
            item.is_read = 1;
            item.read_time = new Date().toISOString();
          }
        });
        this.unreadCount = 0;
        uni.showToast({ title: '全部标记为已读', icon: 'success' });
      } catch (e) {
        console.error('全部标记已读失败', e);
        uni.showToast({ title: '操作失败', icon: 'none' });
      }
    },

    async deleteNotification(item) {
      uni.showModal({
        title: '删除通知',
        content: '确定要删除这条通知吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await myRequest({
                url: `/api/notifications/${item.id}`,
                method: 'DELETE'
              });
              // 从列表中移除
              const index = this.notificationList.findIndex(n => n.id === item.id);
              if (index > -1) {
                this.notificationList.splice(index, 1);
                this.totalCount--;
                if (!item.is_read) {
                  this.unreadCount = Math.max(0, this.unreadCount - 1);
                }
              }
              uni.showToast({ title: '删除成功', icon: 'success' });
            } catch (e) {
              console.error('删除通知失败', e);
              uni.showToast({ title: '删除失败', icon: 'none' });
            }
          }
        }
      });
    },

    async clearReadNotifications() {
      uni.showModal({
        title: '清空已读',
        content: '确定要清空所有已读通知吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await myRequest({
                url: '/api/notifications/clear-read',
                method: 'DELETE'
              });
              // 重新加载列表
              this.page = 1;
              this.fetchNotifications();
              uni.showToast({ title: '清空成功', icon: 'success' });
            } catch (e) {
              console.error('清空失败', e);
              uni.showToast({ title: '清空失败', icon: 'none' });
            }
          }
        }
      });
    },

    async loadMore() {
      this.page++;
      await this.fetchNotifications(true);
    },

    handleNotificationClick(item) {
      // 如果未读，先标记为已读
      if (!item.is_read) {
        this.markAsRead(item);
      }

      // 根据通知类型跳转到相应页面
      if (item.type === 'borrow_due' && item.related_id) {
        // 跳转到借阅记录
        uni.switchTab({ url: '/pages/borrow/borrow' });
      } else if (item.type === 'reservation_available' && item.related_id) {
        // 跳转到预约列表
        uni.navigateTo({ url: '/pages/reservation/list' });
      }
    },

    getTypeIcon(type) {
      const iconMap = {
        'borrow_due': '⏰',
        'reservation_available': '📚',
        'order_approved': '✅',
        'order_rejected': '❌',
        'renew_approved': '✅',
        'renew_rejected': '❌',
        'overdue': '⚠️',
        'system': '📢'
      };
      return iconMap[type] || '📢';
    },

    getTypeText(type) {
      const textMap = {
        'borrow_due': '到期提醒',
        'reservation_available': '预约可借',
        'order_approved': '借阅通过',
        'order_rejected': '借阅驳回',
        'renew_approved': '续借通过',
        'renew_rejected': '续借驳回',
        'overdue': '逾期提醒',
        'system': '系统通知'
      };
      return textMap[type] || '通知';
    },

    getTypeClass(type) {
      const classMap = {
        'borrow_due': 'warning',
        'reservation_available': 'success',
        'order_approved': 'success',
        'order_rejected': 'danger',
        'renew_approved': 'success',
        'renew_rejected': 'danger',
        'overdue': 'danger',
        'system': 'info'
      };
      return classMap[type] || 'info';
    },

    formatTime(timeStr) {
      if (!timeStr) return '';
      const now = new Date();
      const time = new Date(timeStr);
      const diff = now - time;
      const minutes = Math.floor(diff / 60000);
      const hours = Math.floor(diff / 3600000);
      const days = Math.floor(diff / 86400000);

      if (minutes < 1) {
        return '刚刚';
      } else if (minutes < 60) {
        return `${minutes}分钟前`;
      } else if (hours < 24) {
        return `${hours}小时前`;
      } else if (days < 7) {
        return `${days}天前`;
      } else {
        return `${time.getMonth() + 1}-${time.getDate()}`;
      }
    }
  }
};
</script>

<style scoped>
.page {
  background: #f5f5f5;
  min-height: 100vh;
}

.header {
  background: #fff;
  padding: 30rpx 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.stats .total-count {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.stats .unread-count {
  font-size: 24rpx;
  color: #ff4d4f;
  margin-left: 20rpx;
}

.actions {
  display: flex;
  gap: 20rpx;
}

.mark-all-btn,
.clear-btn {
  padding: 12rpx 24rpx;
  font-size: 24rpx;
  border-radius: 6rpx;
  border: none;
}

.mark-all-btn {
  background: #3E88F0;
  color: #fff;
}

.clear-btn {
  background: #f5f5f5;
  color: #666;
}

.content {
  padding: 0 20rpx;
}

.loading, .empty {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
}

.empty-img {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.notification-item {
  background: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
  position: relative;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
}

.notification-item.unread {
  border-left: 6rpx solid #3E88F0;
  background: #f0f9ff;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.notification-type {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.type-icon {
  font-size: 24rpx;
  width: 40rpx;
  height: 40rpx;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  text-align: center;
}

.type-icon.success {
  background: #52c41a;
}

.type-icon.warning {
  background: #ff9900;
}

.type-icon.danger {
  background: #ff4d4f;
}

.type-icon.info {
  background: #1890ff;
}

.type-text {
  font-size: 24rpx;
  color: #666;
}

.notification-time {
  font-size: 22rpx;
  color: #999;
}

.notification-content {
  margin-bottom: 15rpx;
}

.notification-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.notification-text {
  font-size: 26rpx;
  color: #666;
  line-height: 1.4;
  display: block;
}

.notification-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.read-status {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.unread-dot {
  width: 12rpx;
  height: 12rpx;
  background: #ff4d4f;
  border-radius: 50%;
}

.read-text {
  font-size: 22rpx;
  color: #999;
}

.notification-actions {
  display: flex;
  gap: 15rpx;
}

.action-btn {
  padding: 8rpx 16rpx;
  font-size: 22rpx;
  border-radius: 4rpx;
  border: 1rpx solid #d9d9d9;
  background: #fff;
  color: #666;
}

.action-btn.delete {
  color: #ff4d4f;
  border-color: #ff4d4f;
}

.load-more {
  text-align: center;
  padding: 40rpx 0;
  color: #666;
  font-size: 26rpx;
}
</style>
